﻿using MD5Hash;
using MediatR;
using Microsoft.IdentityModel.Tokens;
using NLog.Web.LayoutRenderers;
using SmartCity.Passport.API.Applications.Commands;
using SmartCity.Passport.API.DTOS;
using SmartCity.Passport.API.Extensions;
using SmartCity.Passport.Domain.Entities;
using SmartCity.Passport.ErrorCode;
using SmartCity.Passport.Infrastructure.Interfaces;
using SmartCity.Passport.Infrastructure.Migrations;
using System;
using System.IdentityModel.Tokens.Jwt;
using System.Numerics;
using System.Text;

namespace SmartCity.Passport.API.Applications.CommandHandlers
{
    /// <summary>
    /// 登录处理命令
    /// </summary>
    public class LoginQueryCommandHandler : IRequestHandler<LoginQueryCommand, APIResult<UserDTO>>
    {
        /// <summary>
        /// 用户仓储
        /// </summary>
        private readonly IBaseRespository<User> userRep;
        /// <summary>
        /// 角色仓储
        /// </summary>
        private readonly IBaseRespository<Role> roleRep;
        /// <summary>
        /// 用户角色仓储
        /// </summary>
        private readonly IBaseRespository<RoleUser> roleuserRep;
        /// <summary>
        /// 权限仓储
        /// </summary>
        private readonly IBaseRespository<Permission> permissionRep;
        /// <summary>
        /// 角色权限仓储
        /// </summary>
        private readonly IBaseRespository<RolePermission> rplepermissionRep;
        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="userRep">用户仓储</param>
        /// <param name="roleRep">角色仓储</param>
        /// <param name="roleuserRep">角色用户仓储</param>
        /// <param name="permissionRep">权限仓储</param>
        /// <param name="rplepermissionRep">角色权限</param>
        public LoginQueryCommandHandler(IBaseRespository<User> userRep, IBaseRespository<Role> roleRep, IBaseRespository<RoleUser> roleuserRep, IBaseRespository<permission> permissionRep, IBaseRespository<RolePermission> rplepermissionRep)
        {
            this.userRep = userRep;
            this.roleRep = roleRep;
            this.roleuserRep = roleuserRep;
            //this.permissionRep = permissionRep;
            this.rplepermissionRep = rplepermissionRep;
        }

        /// <summary>
        /// 构造方法
        /// </summary>
        /// <param name="request">请求</param>
        /// <param name="cancellationToken">取消</param>
        /// <returns></returns>
        public Task<APIResult<UserDTO>> Handle(LoginQueryCommand request, CancellationToken cancellationToken)
        {
            APIResult<UserDTO> result=new APIResult<UserDTO>();
            result.Code=APIResultCode.LoginSuccess;
            result.Message=APIResultCode.LoginSuccess.GetDescription();

            //验证
            if (string.IsNullOrWhiteSpace(request.UserName))
            {
                result.Code = APIResultCode.LoginFail;
                result.Message = APIResultCode.LoginFail.GetDescription() + "，用户名不能为空";
                return Task.FromResult(result);
            }
            if (string.IsNullOrWhiteSpace(request.UserPass))
            {
                result.Code = APIResultCode.LoginFail;
                result.Message = APIResultCode.LoginFail.GetDescription() + "，密码不能为空";
                return Task.FromResult(result);
            }

            var res = from a in userRep.GetAll()
                      join b in roleuserRep.GetAll() on a.UserId equals b.UserId
                      join c in roleRep.GetAll() on b.RoleId equals c.RoleId
                      where a.UserName == request.UserName
                      select new UserDTO
                      {
                          UserId=a.UserId,
                          UserName=a.UserName,
                          UserPass=a.UserPass,
                          UserNickname=a.UserNickname,
                          Phone=a.Phone,
                          RoleId=c.RoleId,
                          RoleName=c.RoleName,
                      };
            var entity=res.FirstOrDefault();
            if (entity == null)
            {
                result.Code = APIResultCode.LoginFail;
                result.Message = APIResultCode.LoginFail.GetDescription()+"用户名不存在";
                return Task.FromResult(result);
            }

            //var permission = from a in roleRep.GetAll()
            //                 join b in rplepermissionRep.GetAll() on a.RoleId equals b.RoleId
            //                 join c in permissionRep.GetAll() on b.PermissionId equals c.PermissionId
            //                 where 





            request.UserPass = request.UserPass.GetMD5();
            if (entity.UserPass != request.UserPass)
            {
                result.Code = APIResultCode.LoginFail;
                result.Message = APIResultCode.LoginFail.GetDescription() + "用户名和密码不匹配";
                return Task.FromResult(result);
            }

            result.Code = APIResultCode.LoginSuccess;
            result.Message = APIResultCode.LoginSuccess.GetDescription();
            entity.Token = CreateTokenString();
            result.Data = entity;
            return Task.FromResult(result);

        }
        
        /// <summary>
        /// 生成令牌
        /// </summary>
        /// <returns>返回字符串令牌</returns>
        private string CreateTokenString()
        {
            //私钥
            var secretByte = Encoding.UTF8.GetBytes("kdsfldsflkdslkflkdsflkdslfdslkflk");
            // 非对称加密
            var signingKey = new SymmetricSecurityKey(secretByte);
            // 使用256 生成数字签名
            var signingCredentials = new SigningCredentials(signingKey, SecurityAlgorithms.HmacSha256);
            // 生成Token
            var token = new JwtSecurityToken(
                issuer: "BeiJingBW",
                audience: "BeiJingBW",
                expires: DateTime.Now.AddDays(1), // 一天后过期
                signingCredentials: signingCredentials
            );
            // 生成token 字符串
            var strToken = new JwtSecurityTokenHandler().WriteToken(token);
            return strToken;
        }
    }
}
